package c11.deepCopy;

import org.apache.commons.beanutils.BeanUtils;
import java.util.*;

/**
 * 使用BeanUtils.cloneBean进行属性复制
 * 直接拷贝list是不行的，Msg仍然是同一个对象
 * PS:BeanUtils来自org.apache.commons.beanutils,需要引用两个jar包，在本项目的lib目录下
 */
public class StrategyTest2 {
   private static Map<Integer,StrategyService> serviceMap=new HashMap<>();
   static {
       serviceMap.put(111,new StrategyOneService());
       serviceMap.put(222,new StrategyTwoService());
   }
   public static void main(String[] args) {
       Map<Integer,List<String>> appKeyMap=new HashMap<>();
       //创建appKey=1的消息列表
       List<String> oneList=new ArrayList<>();
       oneList.add("device_id1");
       appKeyMap.put(111,oneList);

       //创建appKey=2的消息列表
       List<String> twoList=new ArrayList<>();
       twoList.add("device_id2");
       appKeyMap.put(222,twoList);

       //创建消息
       List<Msg> msgList=new ArrayList<>();
       Msg msg=new Msg();
       msg.setDataId("abc");
       msg.setBody("hello,二狗子");
       msgList.add(msg);

       //替换msg列表
       Iterator<Integer> appKeyItr= appKeyMap.keySet().iterator();
       Map<Integer,List<Msg>> appKeyMsgMap=new HashMap<>();
       //直接new ArrayList还是浅复制，因为Msg是引用类型，每个消息列表都是对同一个Msg引用
//       while(appKeyItr.hasNext()){
//           appKeyMsgMap.put(appKeyItr.next(),new ArrayList<>(msgList));
//       }
       //单个复制
       while(appKeyItr.hasNext()){
           //复制每个消息到临时消息列表
           List<Msg> tempList=new ArrayList<>();
           Iterator<Msg> itrMsg=msgList.iterator();
           while (itrMsg.hasNext()){
               Msg tempMsg=null;
               try {
                   //复制bean
                   tempMsg=(Msg)BeanUtils.cloneBean(itrMsg.next());
               } catch (Exception e) {
                   e.printStackTrace();
               }
               if(null!=tempMsg){
                   tempList.add(tempMsg);
               }

           }
           appKeyMsgMap.put(appKeyItr.next(),tempList);
       }

       //根据不同的key使用不同的策略进行处理
       appKeyItr= appKeyMap.keySet().iterator();
       while(appKeyItr.hasNext()){
           int appKey=appKeyItr.next();
           StrategyService strategyService=serviceMap.get(appKey);
           if(null !=strategyService){
               strategyService.sendMsg(appKeyMsgMap.get(appKey),appKeyMap.get(appKey));
           }else{
               System.out.println(String.format("appKey:%s,is not registered service",appKey));
           }
       }
   }
}
